package com.zmx.doctor.fragment.wenzhen;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.OrderItemAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.PatientOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.activity.DoctorCertifiedActivity;
import com.zmx.doctor.view.activity.OrderDetailsActivity;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 时间：2020/4/30 15:19
 * 功能：图文问诊
 */
public class GraphicPhysicianFragment extends Fragment {

    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private OrderItemAdapter adapter;
    private List<PatientOrder> lists;

    private View mEmptyLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gp, container, false);

        mEmptyLayout = view.findViewById(R.id.empty);
        reView = view.findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        adapter = new OrderItemAdapter(this.getActivity());
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(GraphicPhysicianFragment.this.getActivity(), OrderDetailsActivity.class);
                intent.putExtra("ask_id", lists.get(listPosition).getId() + "");
                intent.putExtra("type", "1");
                intent.putExtra("patient_id", lists.get(listPosition).getPatient_id() + "");
                startActivity(intent);

            }
        });

        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getData();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            handler.sendEmptyMessage(3);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();
        return view;

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    lists.clear();
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONArray array = new JSONArray(object.getString("data"));
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject jsonObject = array.getJSONObject(i);
                                PatientOrder order = gson.fromJson(jsonObject.toString(), PatientOrder.class);
                                lists.add(order);

                            }

                            adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新


                        }else if(object.getInt("code") == -1){

                            new AlertDialog.Builder(GraphicPhysicianFragment.this.getContext())
                                    .setTitle("温馨提示")
                                    .setMessage("该账户未认证，请先认证")
                                    .setPositiveButton("确定",(dialogInterface, i) -> {

                                        Intent intent = new Intent();
                                        intent.setClass(GraphicPhysicianFragment.this.getContext(), DoctorCertifiedActivity.class);
                                        startActivity(intent);

                                    })
                                    .show().setCancelable(true);

                        }

                        if (lists.size() > 0) {

                            mEmptyLayout.setVisibility(View.GONE);

                        } else {

                            mEmptyLayout.setVisibility(View.VISIBLE);

                        }
                        //刷新加载
                        refreshLayout.finishRefresh(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 3:
                    //刷新加载
                    refreshLayout.finishLoadMore(true);

                    break;
            }
        }
    };

    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add("100");
        ls.add("1");
        ls.add("1");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "askList");
        params.put("data[type]", "1");
        params.put("data[row]", "1");
        params.put("data[number]", "100");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 1, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        requestparams.append(MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();
    }


}